package com.yunhe.authority.service.base.impl;

import com.yunhe.authority.domain.base.MessageCenter;
import com.yunhe.authority.domain.company.Company;
import com.yunhe.authority.model.base.*;
import com.yunhe.authority.repository.base.MessageCenterRepository;
import com.yunhe.authority.service.base.MessageCenterService;
import com.yunhe.authority.service.company.CompanyService;
import com.yunhe.authority.util.MyHeaderUtil;
import com.yunhe.common.constant.MessageConsts;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.model.PageParam;
import com.yunhe.common.util.BeansUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName MessageCenterServiceImpl
 * @Description TODO
 * @Author HeTao
 * @Date 2021/10/18 17:53
 * @Version 1.0
 **/
@Service
public class MessageCenterServiceImpl implements MessageCenterService {

    @Autowired
    private MessageCenterRepository messageCenterRepository;

    @Autowired
    private MyHeaderUtil myHeaderUtil;

    @Autowired
    private CompanyService companyService;


    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public MessageCenter createMessageCenter(MessageCenter messageCenter) {
        return messageCenterRepository.save(messageCenter);
    }


    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public void deleteMessageCenter(Long id) {
        messageCenterRepository.deleteById(id);
    }


    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public MessageCenter updateMessageCenter(MessageCenter messageCenter) {
        return messageCenterRepository.save(messageCenter);
    }


    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public MessageCenter findMessageCenterById(Long id) {
        MessageCenter messageCenter = messageCenterRepository.findById(id).orElse(null);
        if(messageCenter != null){
            if(MessageConsts.WhetherRead.UnRead.value().equals(messageCenter.getWhetherRead())){
                messageCenter.setWhetherRead(MessageConsts.WhetherRead.Read.value());
                messageCenterRepository.save(messageCenter);
            }
        }
        return messageCenter;
    }

    @Override
    public Iterable<MessageCenterVo> findAppMessage(PageParam pageParam) {
        Iterable<MessageCenterVo> result = null;
        Long headerUserId = myHeaderUtil.getHeaderUserId();
        Pageable pageable = PageRequest.of(pageParam.getPage()-1, pageParam.getSize());
        Page<MessageCenter> page = messageCenterRepository.findMessageByCondition(headerUserId,"parkApp",
                "stationUser",pageable);
        if(page != null){
            List<MessageCenter> messageCenters = page.getContent();
            if(!CollectionUtils.isEmpty(messageCenters)){
                List<MessageCenterVo> messageCenterVos = BeansUtil.listCopy(messageCenters, MessageCenterVo.class);
                result  = new PageImpl<MessageCenterVo>(messageCenterVos,pageable,page.getTotalElements());
            }
        }
        return result;
    }

    @Override
    public Iterable<MessageCenterVo> findWeChatMessage(MessageQueryCondition messageQueryCondition) {
        Iterable<MessageCenterVo> result = null;
        Pageable pageable = PageRequest.of(messageQueryCondition.getPage()-1, messageQueryCondition.getSize());
        Page<MessageCenter> page = messageCenterRepository.findWeChatMessage(messageQueryCondition.getCompanyId(),"parkWeChat",
                "companyUser",messageQueryCondition.getUserId(),pageable);
        if(page != null){
            List<MessageCenter> messageCenters = page.getContent();
            if(!CollectionUtils.isEmpty(messageCenters)){
                List<MessageCenterVo> messageCenterVos = BeansUtil.listCopy(messageCenters, MessageCenterVo.class);
                result  = new PageImpl<MessageCenterVo>(messageCenterVos,pageable,page.getTotalElements());
            }
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public void batchCreateMessageCenter(List<MessageCenter> messageCenters) {
        List<MessageCenter> messageCenters1 = new ArrayList<>();
        if(!CollectionUtils.isEmpty(messageCenters)){
            for (MessageCenter messageCenter : messageCenters) {
                //判断之前同种类型的同一条业务是否推送过消息 如果推送过，则更新消息 如果没有推送过，则新增一条消息
                if(messageCenter.getCompanyId() == null){
                    MessageCenter messageCenter1 = messageCenterRepository.findMessageByBusinessIdAndMessageTypeAndMessagePerson(messageCenter.getBusinessId(),
                            messageCenter.getMessageType(),messageCenter.getMessagePerson());
                    if(messageCenter1 != null){
                        messageCenter.setId(messageCenter1.getId());
                    }
                }else {
                    MessageCenter messageCenter1 = messageCenterRepository.findMessageByBusinessIdAndMessageTypeAndCompanyId(messageCenter.getBusinessId(),
                            messageCenter.getMessageType(),messageCenter.getCompanyId());
                    if(messageCenter1 != null){
                        messageCenter.setId(messageCenter1.getId());
                    }
                }
//                MessageCenter save = messageCenterRepository.save(messageCenter);
//                messageCenters1.add(save);
            }
            Iterable<MessageCenter> messageCenters2 = messageCenterRepository.saveAll(messageCenters);
        }
    }

    @Override
    public MessageReadCount getMessageCountByCondition(Long businessId, String messageType) {
        MessageReadCount messageReadCount = new MessageReadCount();
        List<MessageCenter> messageCenters = messageCenterRepository.findMessageByBusinessIdAndMessageType(businessId,messageType);
        if(!CollectionUtils.isEmpty(messageCenters)){
            Map<String, Long> collect = messageCenters.stream().collect(Collectors.groupingBy(MessageCenter::getWhetherRead, Collectors.counting()));
            if(!CollectionUtils.isEmpty(collect)){
                for (Map.Entry<String, Long> entry : collect.entrySet()) {
                    if(MessageConsts.WhetherRead.Read.value().equals(entry.getKey())){
                        messageReadCount.setReadCount(entry.getValue());
                    }else  if(MessageConsts.WhetherRead.UnRead.value().equals(entry.getKey())){
                        messageReadCount.setUnReadCount(entry.getValue());
                    }
                }
            }
        }
        return messageReadCount;
    }

    @Override
    public Iterable<MessageReadVo> findMessageByCondition(WhetherReadQueryCondition whetherReadQueryCondition) {
        Iterable<MessageReadVo> result = null;
        Pageable pageable = PageRequest.of(whetherReadQueryCondition.getPage()-1, whetherReadQueryCondition.getSize());
        Page<MessageCenter> page = messageCenterRepository.findMessageByConditionForWeb(whetherReadQueryCondition.getWhetherRead(),
                whetherReadQueryCondition.getBusinessId(),
                whetherReadQueryCondition.getMessageType(), pageable);
        if(page != null){
            List<MessageCenter> messageCenters = page.getContent();
            if(!CollectionUtils.isEmpty(messageCenters)){
                List<MessageReadVo> messageReadVos = BeansUtil.listCopy(messageCenters, MessageReadVo.class);
                result  = new PageImpl<MessageReadVo>(messageReadVos,pageable,page.getTotalElements());
            }
        }
        return  result;

    }


}
